package com.teng.demo04.controller;

import com.teng.demo04.entity.Book;
import com.teng.demo04.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    BookService bookService;

    @RequestMapping("/bookList")
    public ModelAndView bookList(){
        ModelAndView mv = new ModelAndView();
        List<Book> book = bookService.bookList();
        mv.addObject("book",book);
        mv.setViewName("book/book_list");
        return mv;
    }

    @RequestMapping("/add")
    public ModelAndView addBook(Book book){
        ModelAndView mv = new ModelAndView("book/book_detail");
        mv.addObject("pageTitle","新增书籍");
        return mv;
    }

    @RequestMapping("/update")
    public ModelAndView updateBook(int id){
        ModelAndView mv = new ModelAndView("book/book_detail");
        Book book = bookService.queryBook(id);
        mv.addObject("pageTitle","编辑书籍");
        mv.addObject("book",book);
        return mv;
    }

    @RequestMapping("/save")
    public ModelAndView save(Book book){
        ModelAndView mv = new ModelAndView();
        if (book.getBookID()>0){
            System.out.println(book.getBookID());
            bookService.updateBook(book);
        }
        else {
            bookService.addBook(book);
        }
        mv.setViewName("redirect:/book/bookList");
        return mv;
    }

    @RequestMapping("/delete")
    public ModelAndView deleteBook(int id){
        ModelAndView mv = new ModelAndView();
        bookService.deleteBook(id);
        mv.setViewName("redirect:/book/bookList");
        return mv;
    }

    @RequestMapping("/queryBook")
    public ModelAndView queryBookByName(@RequestParam("bookName") String bookName){
        ModelAndView mv = new ModelAndView("book/book_list");
        if (bookName.equals("")){
            List<Book> booksList = bookService.bookList();
            mv.addObject("book",booksList);
        }
        else {
            List<Book> books = bookService.queryBookByName(bookName);
            mv.addObject("book",books);
        }
        return mv;
    }
}
